/*@Copyright (c) 2025 stray
*@author:	stray
*@date	:	2025-04-21
*@usage	:	升降机上位机
********************************************************************/
#include "lift_upper.h"
#include "ui_lift_upper.h"
#include "stdlib.h"
#include "string.h"
#include"QMessageBox"

template<class T>
void transStruct2QByteArray(const T &_src,QByteArray &qba){
    uint8_t buffer[sizeof(T)];
    memccpy(buffer,_src,sizeof(T));
    qba = QByteArray(buffer);
}



lift_upper::lift_upper(QWidget *parent)
    : QWidget(parent),ui(new Ui::lift_upper)
{
    ui->setupUi(this);
    this->setWindowTitle("升降机构上位机");

    //地址绑定
    this->lift_status.height = 0;
    this->lift_status.behavior= LIFT_STOP;
    this->lift_status.error_type = 1;
    this->ui->label_height->setNum(this->lift_status.height);
    this->ui->label_error_type->setText("正常");
    this->ui->label_status->setText(this->lift_status.behavior==LIFT_STOP?"停止运行":"运行中");


    this->ui->lineEdit_server_ip->setText("192.168.137.198");
    this->ui->spinBox_server_port->setMinimum(128);
    this->ui->spinBox_server_port->setMaximum(65535);
    this->ui->spinBox_server_port->setValue(14250);
    this->ui->spinBox_displacement->setMinimum(-19);
    this->ui->spinBox_displacement->setMaximum(19);
    this->ui->spinBox_displacement->setValue(10);
    this->ui->spinBox_speed->setMinimum(1);
    this->ui->spinBox_speed->setMaximum(19);
    this->ui->spinBox_speed->setValue(10);
    this->localSocket = new QTcpSocket(this);

    //创建connect
    //连接服务器按键
    connect(ui->pushButton_bind,&QPushButton::clicked,this,&lift_upper::buttom_bind_slot);
    //tcp自动更新数据
    connect(localSocket, &QTcpSocket::readyRead, this, &lift_upper::readData);


    //处理时间
    heartbeatTimer = new QTimer(this);
    heartbeatTimer->setInterval(2000);
    // tcpSenderTimer = new QTimer(this);
    // tcpSenderTimer->setInterval(1000);
    //发送数据
    connect(ui->pushButton_start,&QPushButton::clicked, this ,[=](){
        if(ui->pushButton_bind->text()=="断开连接"){
            pushButtom_start_slot();
        }
        else{
            QMessageBox::warning(this,"注意","未连接服务器");
        }
    });
    connect(ui->pushButton_stop,&QPushButton::clicked,this,&lift_upper::pushButtom_stop_slot);

    //心跳检测（每2秒）
    connect(heartbeatTimer, &QTimer::timeout, this, [=](){
        if(ui->pushButton_bind->text()!="请求连接"&&QDateTime::currentMSecsSinceEpoch() - last_receive_time > 5000) {
            qDebug()<<"连接超时，尝试重连...";
            localSocket->abort();
            ui->pushButton_bind->setText("连接中...");
            connectToHost();
        }
    });

}

/*@brief	:	连接按键槽函数
 *@author	:	stray	2025-04-21
 ********************************/
void lift_upper::buttom_bind_slot(){
    if(ui->pushButton_bind->text()=="断开连接"){
        this->lift_control.displacement=0;
        this->lift_control.speed=0;
        uint8_t buffer[20];
        memcpy(buffer,&this->lift_control,sizeof(LIFT_CONTROL));
        localSocket->write((char *)buffer,sizeof(lift_control));
        this->localSocket->close();
        ui->pushButton_bind->setText("请求连接");
        heartbeatTimer->start();
        return;
    }
    ui->pushButton_bind->setText("连接中...");
    heartbeatTimer->start();
    connectToHost();
}

/*@brief	:   读取处理数据
 *@author	:	stray	2025-04-21
 ********************************/
void lift_upper::readData() {
    last_receive_time = QDateTime::currentMSecsSinceEpoch();
    QByteArray temp(localSocket->readAll());
    memcpy(&this->lift_status,temp.constData(),sizeof(lift_status));

    this->ui->label_height->setNum(this->lift_status.height);
    switch(this->lift_status.error_type){
        case NORMAL:
            this->ui->label_error_type->setText("正常");
            break;
        case OVER_SPEED:
            this->ui->label_error_type->setText("速度非法");
            break;
        case ERROR_MOVE:
            this->ui->label_error_type->setText("非法移动");
            break;
        case ERROR_STOP:
            this->ui->label_error_type->setText("失速");
            break;
        case ERROR_DIRCTION:
            this->ui->label_error_type->setText("错向");
            break;
    }
    if(this->lift_status.error_type!=NORMAL){
        this->ui->label_error_type->setStyleSheet("color:red;");
    }
    else{
        this->ui->label_error_type->setStyleSheet("color:black;");
    }
    this->ui->label_status->setText(this->lift_status.behavior==LIFT_STOP?"停止运行":"运行中");
}

/*@brief	:	连接按键槽函数
 *@author	:	stray	2025-04-21
 ********************************/
void lift_upper::connectToHost()
{
    localSocket->connectToHost(ui->lineEdit_server_ip->text(), ui->spinBox_server_port->value());
    ui->pushButton_bind->setText("请求中...");
    if(localSocket->waitForConnected(1000)){
        ui->pushButton_bind->setText("断开连接");
    }
    else{
        ui->pushButton_bind->setText("请求连接");
    }
}

/*@brief	:   启动命令
 *@author	:	stray	2025-04-21
 ********************************/
void lift_upper::pushButtom_start_slot(){
    if(this->lift_status.behavior==LIFT_STOP){
        this->lift_control.displacement=this->ui->spinBox_displacement->value();
        this->lift_control.speed=ui->spinBox_speed->value();
        uint8_t buffer[20];
        memcpy(buffer,&this->lift_control,sizeof(LIFT_CONTROL));
        localSocket->write((char *)buffer,sizeof(LIFT_CONTROL));
    }
    else{
        QMessageBox::warning(this,"注意","程序已经在运行中");
    }
};

/*@brief	:   停止命令
 *@author	:	stray	2025-04-21
 ********************************/
void lift_upper::pushButtom_stop_slot(){
    if(ui->pushButton_bind->text()=="断开连接"){
        this->lift_control.displacement=0;
        this->lift_control.speed=-99;
        localSocket->write((char*)&this->lift_control,sizeof(LIFT_CONTROL));
    }
    else{
        QMessageBox::warning(this,"注意","未连接服务器");
    }
};

lift_upper::~lift_upper()
{
    localSocket->close();
    delete this->localSocket;
    delete ui;
}
